package cn.echo.consul.manager.controller;

import cn.echo.consul.manager.annotation.RequestPermissions;
import cn.echo.consul.manager.entity.vo.ProjectInfoVo;
import cn.echo.consul.manager.enums.PermissionRole;
import cn.echo.consul.manager.service.ProjectInfoService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

import static cn.echo.consul.manager.constant.HeaderFields.AUTH_USER_ID;
import static cn.echo.consul.manager.enums.PermissionRole.*;

/**
 * 项目信息管理
 * @author lonyee
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/project")
public class ProjectInfoController {

    @Resource
    final ProjectInfoService projectInfoService;

    /**
     * 获取环境列表
     */
    @GetMapping("/envs")
    public List<String> getEnvs() {
        return projectInfoService.getEnvs();
    }

    /**
     * 获取用户有权限项目列表
     * @return
     */
    @GetMapping("/list")
    public List<ProjectInfoVo> getProjects(@RequestAttribute(AUTH_USER_ID) String userId, String searchKey) {
        return projectInfoService.getProjects(userId, searchKey);
    }

    /**
     * 获取项目信息
     * @return
     */
    @GetMapping("/info")
    @RequestPermissions({ ADMIN, OWNER, PARTNER, VIEWER })
    public ProjectInfoVo getProject(@RequestAttribute(AUTH_USER_ID) String userId, String projectId) {
        return projectInfoService.getProject(userId, projectId);
    }

    /**
     * 添加项目信息
     */
    @PostMapping("/append")
    public void appendProject(@RequestAttribute(AUTH_USER_ID) String userId,
                              String projectId, String projectDesc, String[] envs) {
        projectInfoService.appendProject(userId, projectId, projectDesc, Arrays.asList(envs));
    }

    /**
     * 修改项目信息
     */
    @PostMapping("/modify")
    @RequestPermissions({ ADMIN, OWNER })
    public void modifyProject(@RequestAttribute(AUTH_USER_ID) String userId,
                              String projectId, String projectDesc, Boolean usable, String[] envs) {
        projectInfoService.modifyProject(userId, projectId, projectDesc, usable, Arrays.asList(envs));
    }

    /**
     * 设置项目的用户权限
     */
    @PostMapping("/permission/modify")
    @RequestPermissions({ ADMIN, OWNER })
    public void modifyUserPermission(@RequestAttribute(AUTH_USER_ID) String authorId,
                                     String userId, String projectId, PermissionRole role) {
        projectInfoService.modifyUserPermission(userId, projectId, role, authorId);
    }

    /**
     * 移除项目的用户权限
     */
    @PostMapping("/permission/remove")
    @RequestPermissions({ ADMIN, OWNER })
    public void removeUserPermission(@RequestAttribute(AUTH_USER_ID) String authorId,
                                     String userId, String projectId) {
        projectInfoService.removeUserPermission(authorId, userId, projectId);
    }
}
